class EventCenter {
  private eventDic: Map<string, Function[]> = new Map()

  on(eventName: string, cb: Function, ctx?: unknown) {
    const fn = ctx ? cb.bind(ctx) : cb
    if (!this.eventDic.has(eventName)) {
      this.eventDic.set(eventName, [fn])
    } else {
      this.eventDic.get(eventName).push(fn)
    }
  }
  off(eventName: string, cb: Function) {
    if (!this.eventDic.has(eventName)) {
      return
    }
    const fns = this.eventDic.get(eventName)
    fns.splice(fns.indexOf(cb), 1)
  }
  emit(eventName: string, ...args) {
    if (!this.eventDic.has(eventName)) {
      return
    }
    const fns = this.eventDic.get(eventName)
    fns.forEach(fn => {
      fn(...args)
    })
  }
  clear() {
    this.eventDic.clear()
  }
}

export default new EventCenter()
